package com.mmlc.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.TextView;

@SuppressWarnings({"unchecked"})
public class ViewUtils {

    public static class ViewHolder {
        public static <T extends View> T get(View view, int id) {
            SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
            if (viewHolder == null) {
                viewHolder = new SparseArray<View>();
                view.setTag(viewHolder);
            }
            View childView = viewHolder.get(id);
            if (childView == null) {
                childView = view.findViewById(id);
                viewHolder.put(id, childView);
            }
            return (T) childView;
        }
    }

    public static <T extends View> T getView(Activity activity, int id) {
        try {
            return (T) activity.findViewById(id);
        } catch (ClassCastException ex) {
            Log.e("Activity", "Could not cast View to concrete class.", ex);
            throw ex;
        }
    }

    public static <T extends View> T getView(View view, int id) {
        try {
            return (T) view.findViewById(id);
        } catch (ClassCastException ex) {
            Log.e("Fragment", "Could not cast View to concrete class.", ex);
            throw ex;
        }
    }

    public static <T extends View> T getView(AlertDialog dialog, int id) {
        try {
            return (T) dialog.findViewById(id);
        } catch (ClassCastException ex) {
            Log.e("Fragment", "Could not cast View to concrete class.", ex);
            throw ex;
        }
    }

    public static int LEFT = 1, TOP = 2, RIGHT = 3, BOTTOM = 4;

    public static void setStatusDrawable(Context context, TextView view, int drawableId, int location) {
        if (drawableId != 0) {
            Drawable drawable = context.getResources().getDrawable(drawableId);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            view.setCompoundDrawables(location == LEFT ? drawable : null, location == TOP ? drawable : null, location == RIGHT ? drawable : null, location == BOTTOM ? drawable : null);
        } else {

        }
    }

    public static boolean isEmpty(String str) {
        return str == null || "".equals(str) || "null".equals(str);
    }

    public static boolean equals(String value1, String value2) {
        return equals(value1.toCharArray(), value2.toCharArray());
    }

    public static boolean equals(char[] value1, char[] value2) {
        if (value1.length != value2.length)
            return false;
        for (int i = 0; i < value1.length; i++) {
            if (value1[i] != value2[i])
                return false;
        }
        return true;
    }

}
